// 导航守卫
import router from '@/router'
import store from '@/store'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { cancelAll } from './utils/request'

const whiteArr = ['/404', '/login']
Nprogress.start()
router.beforeEach(async(to, from, next) => {
  cancelAll()
  // 如果有token
  if (store.getters.token) {
    // 如果跳转到登录页
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      // 验证token  通过调用接口获取用户信息判断是否能调成功以验证token是否有效
      // 判断是否有用户数据,没有就调接口
      if (!store.state.user.userInfo) {
        await store.dispatch('user/getUserInfo')
        // addRoutes 的缺陷,需要再经历一次导航守卫才能正常访问
        next(to.fullPath)
      } else {
        next()
      }
    }
  } else {
    // console.log(to)
    if (whiteArr.includes(to.path.toLowerCase())) {
      next()
    } else {
      // encodeURIComponent  加密字符
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
    }
  }
  Nprogress.done()
})
